package com.strato.transaction.v1_0_0.api.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import com.strato.transaction.v1_0_0.api.TransactionStatus;

public class DataSourceTransactionStatus implements TransactionStatus {

	private Map<DataSource,Connection> connections;
	
	@Override
	public Connection getConnection(DataSource datasource) {
		if(connections==null){
			connections=new HashMap<DataSource,Connection>();
		}
		Connection connection = connections.get(datasource);
		if(connection==null){
			try {
				connection=datasource.getConnection();
				connection.setAutoCommit(false);
				if(connections==null){
					connections=new HashMap<DataSource,Connection>();
				}
				connections.put(datasource, connection);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		return connection;
	}

	public void close(){
		if(connections==null){
			return;
		}
		for(Iterator<Entry<DataSource, Connection>> iter = connections.entrySet().iterator();iter.hasNext();){
			Entry<DataSource, Connection> entry = iter.next();
			Connection connection=entry.getValue();
			if(connection!=null){
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		connections=null;
	}

	@Override
	public void rollback() {
		if(connections==null){
			return;
		}
		for(Iterator<Entry<DataSource, Connection>> iter = connections.entrySet().iterator();iter.hasNext();){
			Entry<DataSource, Connection> entry = iter.next();
			Connection connection=entry.getValue();
			if(connection!=null){
				try {
					connection.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void commit() {
		if(connections==null){
			return;
		}
		for(Iterator<Entry<DataSource, Connection>> iter = connections.entrySet().iterator();iter.hasNext();){
			Entry<DataSource, Connection> entry = iter.next();
			Connection connection=entry.getValue();
			if(connection!=null){
				try {
					connection.commit();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
